import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:im_app/im/page/sub/ContentSearchResultPage.dart';
import 'package:im_app/im/page/view/ListSeparator.dart';
import 'package:provider/provider.dart';
import '../../dao/ImSessionDao.dart';
import '../../pojo/ImPojo.dart';
import '../../pojo/UiPojo.dart';
import '../../util/ImCacheFactory.dart';
import '../../util/ImConstant.dart';
import '../../util/ImSingleton.dart';
import '../bloc/ContentSearchCubit.dart';
import '../bloc/SessionListCubit.dart';
import '../view/LoadingView.dart';
import '../view/ContentSearchView.dart';
import '../view/component/GroupIconView.dart';
import '../view/component/SessionIconView.dart';
import '../view/component/UserIconView.dart';

/// 内容查询页面  查找用户，群组，消息
class ContentSearchPage extends StatefulWidget {

  const ContentSearchPage({super.key});

  @override
  State<StatefulWidget> createState() => new _ContentSearchState();
}

class _ContentSearchState extends State<ContentSearchPage> {
  final controller = TextEditingController();

  var _searchText = '';
  var _userMaxSize = 5;
  var _userDefaultSize = 5;

  var _groupMaxSize = 5;
  var _groupDefaultSize = 5;

  var _messageMaxSize = 5;
  var _messageDefaultSize = 5;

  @override
  void initState() {
    super.initState();
    var messageSearchCubit = context.read<ContentSearchCubit>();
    messageSearchCubit.init();
  }

  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ImConstant.IM_MAIN_BACKGROUND_COLOR,
      body: SafeArea(
        left: false, right: false,
        child: Column(
          children: [
            Padding(
              padding: const EdgeInsets.only(left: 5, right: 5, top: 10),
              child: ContentSearchView(searchHandler: _doSearch,),),
            Expanded(child: _buildSearchResultPane(context)),
          ],
        ),
      )
    );
  }

  Widget _buildSearchResultPane(BuildContext context) {
    var contentSearchCubit = context.watch<ContentSearchCubit>();
    var children = <Widget>[];
    // 查找联系人
    if (contentSearchCubit.state.userSearchResults.isNotEmpty) {
      var sliverAppbar = _buildSearchTitle("联系人");
      children.add(sliverAppbar);

      var length = contentSearchCubit.state.userSearchResults.length;
      var sliverList = _buildSliverList(contentSearchCubit.state.userSearchResults, length, _userMaxSize);
      children.add(sliverList);

      Widget? moreWidget = _buildMorePane(length, _userMaxSize, _userDefaultSize,
              ()=>_userMaxSize += 10, ()=>_userMaxSize = _userDefaultSize);
      if (moreWidget != null) {
        children.add(moreWidget);
      }
    }

    // 查找用户
    if (contentSearchCubit.state.groupSearchResults.isNotEmpty) {
      var sliverAppbar = _buildSearchTitle('群聊');;
      children.add(sliverAppbar);

      var length = contentSearchCubit.state.groupSearchResults.length;
      var sliverList = _buildSliverList(contentSearchCubit.state.groupSearchResults, length, _groupMaxSize);
      children.add(sliverList);

      Widget? moreWidget = _buildMorePane(length, _groupMaxSize, _groupDefaultSize,
              ()=>_groupMaxSize += 10, ()=>_groupMaxSize = _groupDefaultSize);
      if (moreWidget != null) {
        children.add(moreWidget);
      }
    }

    // 查找消息
    if (contentSearchCubit.state.messageSearchResults.length > 0) {
      var sliverAppbar = _buildSearchTitle('消息');
      children.add(sliverAppbar);

      var length = contentSearchCubit.state.messageSearchResults.length;
      var sliverList = _buildSliverList(contentSearchCubit.state.messageSearchResults, length, _messageMaxSize);
      children.add(sliverList);

      Widget? moreWidget = _buildMorePane(length, _messageMaxSize, _messageDefaultSize,
              ()=>_messageMaxSize += 10, ()=>_messageMaxSize = _messageDefaultSize);
      if (moreWidget != null) {
        children.add(moreWidget);
      }
    }

    return LoadingView(state: contentSearchCubit.state.state, child: CustomScrollView(slivers: children));
  }

  Widget _buildSearchTitle(String title) {
    return SliverPadding(padding: EdgeInsets.only(top: 10),
        sliver: SliverToBoxAdapter(child:
          Container(color:
            Colors.black12,
            padding: EdgeInsets.only(left: 10, top: 5, bottom: 5),
            margin: EdgeInsets.only(top: 5, bottom: 5),
            child: Text(title),
          ),
        )
    );
  }

  Widget _buildListTitle(SearchResult searchResult) {
    if (searchResult.session != null) {
      return _buildMessageListTitle(searchResult);
    } else if (searchResult.groupCode != null) {
      return _buildGroupListTitle(searchResult);
    } else {
      return _buildUserListTitle(searchResult);
    }
  }

  Widget _buildUserListTitle(SearchResult searchResult) {
    return ListTile(
      leading: UserIconView(user: searchResult.user!, iconSize: ImConstant.IM_USER_ICON_SIZE - 10,),
      title: Text(searchResult.userName??'')
    );
  }

  Widget _buildGroupListTitle(SearchResult searchResult) {
    return ListTile(
      leading: GroupIconView(group: searchResult.group!, iconSize: ImConstant.IM_USER_ICON_SIZE - 10,),
      title: Text(searchResult.groupName??''),
      subtitle: Text(searchResult.userName??'', style: const TextStyle(fontSize: 12),),
    );
  }

  Widget _buildMessageListTitle(SearchResult searchResult) {
    return ListTile(
      leading: SessionIconView(session: searchResult.session!, iconSize: ImConstant.IM_USER_ICON_SIZE - 10,),
      title: Text(searchResult.session?.name??''),
      subtitle: Text('包含\"${_searchText}\"消息${searchResult.messageTotal}个'),
    );
  }

  void _doSearch(BuildContext context, String searchText) {
    var messageSearchCubit = context.read<ContentSearchCubit>();
    if (searchText != '') {
      _searchText = searchText;
      messageSearchCubit.search(searchText);
    }
  }

  Widget? _buildMorePane(int length, int maxSize, int defaultSize, Function moreFunction, Function unExpandFunction) {
    if (length > maxSize) { // 有更多查询结果
      if (_userDefaultSize != _userMaxSize) {
          return SliverToBoxAdapter(child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Expanded(child:
                InkWell(child: const Padding(padding: EdgeInsets.only(top: 10, bottom: 10), child:
                  Center(child:
                    Text('更多...', style: TextStyle(fontSize: 16),),
                  ),
                ),
                onTap: () {stateChange(moreFunction);}
                )
              ),
              Expanded(child:
                InkWell(child: const Padding(padding: EdgeInsets.only(top:10, bottom: 10), child:
                  Center(child: Text('收起', style: TextStyle(fontSize: 16),),
                  ),),
                  onTap: () {stateChange(unExpandFunction);},
                )
              ),
            ],
          ));
      } else {
        return _buildMoreNode(Center(child: Text('更多...', style: TextStyle(fontSize: 16), textAlign: TextAlign.center,),), moreFunction);
      }
    } else if (_userDefaultSize != _userMaxSize) {
      return _buildMoreNode(Center(child: Text('收起', style: TextStyle(fontSize: 16),),), unExpandFunction);
    }
  }

  Widget _buildMoreNode(Widget child, Function onTap) {
    return SliverToBoxAdapter(child: InkWell(child: Padding(padding: EdgeInsets.only(top: 10, bottom: 10), child: child),
      onTap: ()=> stateChange(onTap),));
  }

  Widget _buildSliverList(List<SearchResult> searchResults, int size, int dataMaxSize) {
    var length = searchResults.length;
    var size = length;
    if (length > dataMaxSize) {
      size = dataMaxSize;
    }

    return SliverList.separated(itemBuilder: (BuildContext context, int index) {
      return InkWell(child: _buildListTitle(searchResults[index]),
        onTap: () {
          _showSendMessage(context, searchResults[index]);
        },
      );
      },
      itemCount: size,
      separatorBuilder: (BuildContext context, int index) {
          return ListSeparator();
      },
    );
  }

  void _showSendMessage(BuildContext context, SearchResult searchResult) async {
    var userId = await ImSingleton.getInstance().session.userId;
    ImSession? imSession;

    var sessionDao = ImSessionDao();

    if (searchResult.session != null) {
      Navigator.push(context, MaterialPageRoute(builder: (context) => ContentSearchResultPage(contentSearch:
      _searchText, session: searchResult.session!,)),);
      return;
    } else if (searchResult.userId != null && searchResult.groupCode == null) {
      var session = await sessionDao.getByUserId(userId!, userId, searchResult.userId!);
      if (session == null) {
        var imUser = await ImCacheFactory.getInstance().getImUser(searchResult.userId!);
        imSession = ImSession.buildWithUser(userId, imUser);
        await sessionDao.insert(imSession);
      } else {
        imSession = session;
      }
    } else if (searchResult.groupCode != null) {
      var session = await sessionDao.getByGroupCodeAndUserId(searchResult.groupCode!, userId!);
      if (session == null) {
        var imGroup = await ImCacheFactory.getInstance().getImGroup(userId!, searchResult.groupCode!);
        imSession = ImSession.buildWithGroup(userId, imGroup!);
        await sessionDao.insert(imSession);
      } else {
        imSession = session;
      }
    }

    if (imSession != null) {
      SessionListCubit sessionListCubit = Provider.of<SessionListCubit>(context, listen: false);
      sessionListCubit.addSession(imSession);
      Navigator.of(context).pushNamedAndRemoveUntil("/MessageSendPage", ModalRoute.withName('/MainPage'), arguments: {"id": imSession?.id!, "name": imSession?.name});
    }
  }

  void stateChange(Function function) {
    setState(() {
      function.call();
    });
  }
}
